home *** CD-ROM | disk | FTP | other *** search
/ isnet Internet / Isnet Internet CD.iso / prog / hiz / 09 / 09.exe / adynware.exe / perl / lib / Math / Complex.pm < prev    next >
Encoding:
Text File  |  1999-12-28  |  26.7 KB  |  1,090 lines

  1.  
  2. require Exporter;
  3. package Math::Complex;
  4.  
  5. use strict;
  6.  
  7. use vars qw($VERSION @ISA
  8.         @EXPORT %EXPORT_TAGS
  9.         $package $display
  10.         $i $logn %logn);
  11.  
  12. @ISA = qw(Exporter);
  13.  
  14. $VERSION = 1.01;
  15.  
  16. my @trig = qw(
  17.           pi
  18.           sin cos tan
  19.           csc cosec sec cot cotan
  20.           asin acos atan
  21.           acsc acosec asec acot acotan
  22.           sinh cosh tanh
  23.           csch cosech sech coth cotanh
  24.           asinh acosh atanh
  25.           acsch acosech asech acoth acotanh
  26.          );
  27.  
  28. @EXPORT = (qw(
  29.          i Re Im arg
  30.          sqrt exp log ln
  31.          log10 logn cbrt root
  32.          cplx cplxe
  33.          ),
  34.        @trig);
  35.  
  36. %EXPORT_TAGS = (
  37.     'trig' => [@trig],
  38. );
  39.  
  40. use overload
  41.     '+'    => \&plus,
  42.     '-'    => \&minus,
  43.     '*'    => \&multiply,
  44.     '/'    => \÷,
  45.     '**'    => \&power,
  46.     '<=>'    => \&spaceship,
  47.     'neg'    => \&negate,
  48.     '~'    => \&conjugate,
  49.     'abs'    => \&abs,
  50.     'sqrt'    => \&sqrt,
  51.     'exp'    => \&exp,
  52.     'log'    => \&log,
  53.     'sin'    => \&sin,
  54.     'cos'    => \&cos,
  55.     'tan'    => \&tan,
  56.     'atan2'    => \&atan2,
  57.     qw("" stringify);
  58.  
  59.  
  60. $package = 'Math::Complex';        # Package name
  61. $display = 'cartesian';            # Default display format
  62.  
  63.  
  64. sub make {
  65.     my $self = bless {}, shift;
  66.     my ($re, $im) = @_;
  67.     $self->{'cartesian'} = [$re, $im];
  68.     $self->{c_dirty} = 0;
  69.     $self->{p_dirty} = 1;
  70.     return $self;
  71. }
  72.  
  73. sub emake {
  74.     my $self = bless {}, shift;
  75.     my ($rho, $theta) = @_;
  76.     $theta += pi() if $rho < 0;
  77.     $self->{'polar'} = [abs($rho), $theta];
  78.     $self->{p_dirty} = 0;
  79.     $self->{c_dirty} = 1;
  80.     return $self;
  81. }
  82.  
  83. sub new { &make }        # For backward compatibility only.
  84.  
  85. sub cplx {
  86.     my ($re, $im) = @_;
  87.     return $package->make($re, defined $im ? $im : 0);
  88. }
  89.  
  90. sub cplxe {
  91.     my ($rho, $theta) = @_;
  92.     return $package->emake($rho, defined $theta ? $theta : 0);
  93. }
  94.  
  95.  
  96. use constant pi => 4 * atan2(1, 1);
  97.  
  98.  
  99. use constant log10inv => 1 / log(10);
  100.  
  101. sub i () {
  102.         return $i if ($i);
  103.     $i = bless {};
  104.     $i->{'cartesian'} = [0, 1];
  105.     $i->{'polar'}     = [1, pi/2];
  106.     $i->{c_dirty} = 0;
  107.     $i->{p_dirty} = 0;
  108.     return $i;
  109. }
  110.  
  111.  
  112. sub cartesian {$_[0]->{c_dirty} ?
  113.            $_[0]->update_cartesian : $_[0]->{'cartesian'}}
  114. sub polar     {$_[0]->{p_dirty} ?
  115.            $_[0]->update_polar : $_[0]->{'polar'}}
  116.  
  117. sub set_cartesian { $_[0]->{p_dirty}++; $_[0]->{'cartesian'} = $_[1] }
  118. sub set_polar     { $_[0]->{c_dirty}++; $_[0]->{'polar'} = $_[1] }
  119.  
  120. sub update_cartesian {
  121.     my $self = shift;
  122.     my ($r, $t) = @{$self->{'polar'}};
  123.     $self->{c_dirty} = 0;
  124.     return $self->{'cartesian'} = [$r * cos $t, $r * sin $t];
  125. }
  126.  
  127. sub update_polar {
  128.     my $self = shift;
  129.     my ($x, $y) = @{$self->{'cartesian'}};
  130.     $self->{p_dirty} = 0;
  131.     return $self->{'polar'} = [0, 0] if $x == 0 && $y == 0;
  132.     return $self->{'polar'} = [sqrt($x*$x + $y*$y), atan2($y, $x)];
  133. }
  134.  
  135. sub plus {
  136.     my ($z1, $z2, $regular) = @_;
  137.     my ($re1, $im1) = @{$z1->cartesian};
  138.     $z2 = cplx($z2) unless ref $z2;
  139.     my ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
  140.     unless (defined $regular) {
  141.         $z1->set_cartesian([$re1 + $re2, $im1 + $im2]);
  142.         return $z1;
  143.     }
  144.     return (ref $z1)->make($re1 + $re2, $im1 + $im2);
  145. }
  146.  
  147. sub minus {
  148.     my ($z1, $z2, $inverted) = @_;
  149.     my ($re1, $im1) = @{$z1->cartesian};
  150.     $z2 = cplx($z2) unless ref $z2;
  151.     my ($re2, $im2) = @{$z2->cartesian};
  152.     unless (defined $inverted) {
  153.         $z1->set_cartesian([$re1 - $re2, $im1 - $im2]);
  154.         return $z1;
  155.     }
  156.     return $inverted ?
  157.         (ref $z1)->make($re2 - $re1, $im2 - $im1) :
  158.         (ref $z1)->make($re1 - $re2, $im1 - $im2);
  159.  
  160. }
  161.  
  162. sub multiply {
  163.     my ($z1, $z2, $regular) = @_;
  164.     my ($r1, $t1) = @{$z1->polar};
  165.     $z2 = cplxe(abs($z2), $z2 >= 0 ? 0 : pi) unless ref $z2;
  166.     my ($r2, $t2) = @{$z2->polar};
  167.     unless (defined $regular) {
  168.         $z1->set_polar([$r1 * $r2, $t1 + $t2]);
  169.         return $z1;
  170.     }
  171.     return (ref $z1)->emake($r1 * $r2, $t1 + $t2);
  172. }
  173.  
  174. sub _divbyzero {
  175.     my $mess = "$_[0]: Division by zero.\n";
  176.  
  177.     if (defined $_[1]) {
  178.     $mess .= "(Because in the definition of $_[0], the divisor ";
  179.     $mess .= "$_[1] " unless ($_[1] eq '0');
  180.     $mess .= "is 0)\n";
  181.     }
  182.  
  183.     my @up = caller(1);
  184.     
  185.     $mess .= "Died at $up[1] line $up[2].\n";
  186.  
  187.     die $mess;
  188. }
  189.  
  190. sub divide {
  191.     my ($z1, $z2, $inverted) = @_;
  192.     my ($r1, $t1) = @{$z1->polar};
  193.     $z2 = cplxe(abs($z2), $z2 >= 0 ? 0 : pi) unless ref $z2;
  194.     my ($r2, $t2) = @{$z2->polar};
  195.     unless (defined $inverted) {
  196.         _divbyzero "$z1/0" if ($r2 == 0);
  197.         $z1->set_polar([$r1 / $r2, $t1 - $t2]);
  198.         return $z1;
  199.     }
  200.     if ($inverted) {
  201.         _divbyzero "$z2/0" if ($r1 == 0);
  202.         return (ref $z1)->emake($r2 / $r1, $t2 - $t1);
  203.     } else {
  204.         _divbyzero "$z1/0" if ($r2 == 0);
  205.         return (ref $z1)->emake($r1 / $r2, $t1 - $t2);
  206.     }
  207. }
  208.  
  209. sub _zerotozero {
  210.     my $mess = "The zero raised to the zeroth power is not defined.\n";
  211.  
  212.     my @up = caller(1);
  213.     
  214.     $mess .= "Died at $up[1] line $up[2].\n";
  215.  
  216.     die $mess;
  217. }
  218.  
  219. sub power {
  220.     my ($z1, $z2, $inverted) = @_;
  221.     my $z1z = $z1 == 0;
  222.     my $z2z = $z2 == 0;
  223.     _zerotozero if ($z1z and $z2z);
  224.     if ($inverted) {
  225.         return 0 if ($z2z);
  226.         return 1 if ($z1z or $z2 == 1);
  227.     } else {
  228.         return 0 if ($z1z);
  229.         return 1 if ($z2z or $z1 == 1);
  230.     }
  231.     $z2 = cplx($z2) unless ref $z2;
  232.     unless (defined $inverted) {
  233.         my $z3 = exp($z2 * log $z1);
  234.         $z1->set_cartesian([@{$z3->cartesian}]);
  235.         return $z1;
  236.     }
  237.     return exp($z2 * log $z1) unless $inverted;
  238.     return exp($z1 * log $z2);
  239. }
  240.  
  241. sub spaceship {
  242.     my ($z1, $z2, $inverted) = @_;
  243.     my ($re1, $im1) = ref $z1 ? @{$z1->cartesian} : ($z1, 0);
  244.     my ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
  245.     my $sgn = $inverted ? -1 : 1;
  246.     return $sgn * ($re1 <=> $re2) if $re1 != $re2;
  247.     return $sgn * ($im1 <=> $im2);
  248. }
  249.  
  250. sub negate {
  251.     my ($z) = @_;
  252.     if ($z->{c_dirty}) {
  253.         my ($r, $t) = @{$z->polar};
  254.         return (ref $z)->emake($r, pi + $t);
  255.     }
  256.     my ($re, $im) = @{$z->cartesian};
  257.     return (ref $z)->make(-$re, -$im);
  258. }
  259.  
  260. sub conjugate {
  261.     my ($z) = @_;
  262.     if ($z->{c_dirty}) {
  263.         my ($r, $t) = @{$z->polar};
  264.         return (ref $z)->emake($r, -$t);
  265.     }
  266.     my ($re, $im) = @{$z->cartesian};
  267.     return (ref $z)->make($re, -$im);
  268. }
  269.  
  270. sub abs {
  271.     my ($z) = @_;
  272.     return abs($z) unless ref $z;
  273.     my ($r, $t) = @{$z->polar};
  274.     return abs($r);
  275. }
  276.  
  277. sub arg {
  278.     my ($z) = @_;
  279.     return ($z < 0 ? pi : 0) unless ref $z;
  280.     my ($r, $t) = @{$z->polar};
  281.     return $t;
  282. }
  283.  
  284. sub sqrt {
  285.     my ($z) = @_;
  286.     $z = cplx($z, 0) unless ref $z;
  287.     my ($r, $t) = @{$z->polar};
  288.     return (ref $z)->emake(sqrt($r), $t/2);
  289. }
  290.  
  291. sub cbrt {
  292.     my ($z) = @_;
  293.     return cplx($z, 0) ** (1/3) unless ref $z;
  294.     my ($r, $t) = @{$z->polar};
  295.     return (ref $z)->emake($r**(1/3), $t/3);
  296. }
  297.  
  298. sub _rootbad {
  299.     my $mess = "Root $_[0] not defined, root must be positive integer.\n";
  300.  
  301.     my @up = caller(1);
  302.     
  303.     $mess .= "Died at $up[1] line $up[2].\n";
  304.  
  305.     die $mess;
  306. }
  307.  
  308. sub root {
  309.     my ($z, $n) = @_;
  310.     _rootbad($n) if ($n < 1 or int($n) != $n);
  311.     my ($r, $t) = ref $z ? @{$z->polar} : (abs($z), $z >= 0 ? 0 : pi);
  312.     my @root;
  313.     my $k;
  314.     my $theta_inc = 2 * pi / $n;
  315.     my $rho = $r ** (1/$n);
  316.     my $theta;
  317.     my $complex = ref($z) || $package;
  318.     for ($k = 0, $theta = $t / $n; $k < $n; $k++, $theta += $theta_inc) {
  319.         push(@root, $complex->emake($rho, $theta));
  320.     }
  321.     return @root;
  322. }
  323.  
  324. sub Re {
  325.     my ($z) = @_;
  326.     return $z unless ref $z;
  327.     my ($re, $im) = @{$z->cartesian};
  328.     return $re;
  329. }
  330.  
  331. sub Im {
  332.     my ($z) = @_;
  333.     return 0 unless ref $z;
  334.     my ($re, $im) = @{$z->cartesian};
  335.     return $im;
  336. }
  337.  
  338. sub exp {
  339.     my ($z) = @_;
  340.     $z = cplx($z, 0) unless ref $z;
  341.     my ($x, $y) = @{$z->cartesian};
  342.     return (ref $z)->emake(exp($x), $y);
  343. }
  344.  
  345. sub log {
  346.     my ($z) = @_;
  347.     $z = cplx($z, 0) unless ref $z;
  348.     my ($x, $y) = @{$z->cartesian};
  349.     my ($r, $t) = @{$z->polar};
  350.     $t -= 2 * pi if ($t >  pi() and $x < 0);
  351.     $t += 2 * pi if ($t < -pi() and $x < 0);
  352.     return (ref $z)->make(log($r), $t);
  353. }
  354.  
  355. sub ln { Math::Complex::log(@_) }
  356.  
  357.  
  358. sub log10 {
  359.     my ($z) = @_;
  360.  
  361.     return log(cplx($z, 0)) * log10inv unless ref $z;
  362.     my ($r, $t) = @{$z->polar};
  363.     return (ref $z)->make(log($r) * log10inv, $t * log10inv);
  364. }
  365.  
  366. sub logn {
  367.     my ($z, $n) = @_;
  368.     $z = cplx($z, 0) unless ref $z;
  369.     my $logn = $logn{$n};
  370.     $logn = $logn{$n} = log($n) unless defined $logn;    # Cache log(n)
  371.     return log($z) / $logn;
  372. }
  373.  
  374. sub cos {
  375.     my ($z) = @_;
  376.     $z = cplx($z, 0) unless ref $z;
  377.     my ($x, $y) = @{$z->cartesian};
  378.     my $ey = exp($y);
  379.     my $ey_1 = 1 / $ey;
  380.     return (ref $z)->make(cos($x) * ($ey + $ey_1)/2,
  381.                   sin($x) * ($ey_1 - $ey)/2);
  382. }
  383.  
  384. sub sin {
  385.     my ($z) = @_;
  386.     $z = cplx($z, 0) unless ref $z;
  387.     my ($x, $y) = @{$z->cartesian};
  388.     my $ey = exp($y);
  389.     my $ey_1 = 1 / $ey;
  390.     return (ref $z)->make(sin($x) * ($ey + $ey_1)/2,
  391.                   cos($x) * ($ey - $ey_1)/2);
  392. }
  393.  
  394. sub tan {
  395.     my ($z) = @_;
  396.     my $cz = cos($z);
  397.     _divbyzero "tan($z)", "cos($z)" if ($cz == 0);
  398.     return sin($z) / $cz;
  399. }
  400.  
  401. sub sec {
  402.     my ($z) = @_;
  403.     my $cz = cos($z);
  404.     _divbyzero "sec($z)", "cos($z)" if ($cz == 0);
  405.     return 1 / $cz;
  406. }
  407.  
  408. sub csc {
  409.     my ($z) = @_;
  410.     my $sz = sin($z);
  411.     _divbyzero "csc($z)", "sin($z)" if ($sz == 0);
  412.     return 1 / $sz;
  413. }
  414.  
  415. sub cosec { Math::Complex::csc(@_) }
  416.  
  417. sub cot {
  418.     my ($z) = @_;
  419.     my $sz = sin($z);
  420.     _divbyzero "cot($z)", "sin($z)" if ($sz == 0);
  421.     return cos($z) / $sz;
  422. }
  423.  
  424. sub cotan { Math::Complex::cot(@_) }
  425.  
  426. sub acos {
  427.     my ($z) = @_;
  428.     $z = cplx($z, 0) unless ref $z;
  429.     return ~i * log($z + (Re($z) * Im($z) > 0 ? 1 : -1) * sqrt($z*$z - 1));
  430. }
  431.  
  432. sub asin {
  433.     my ($z) = @_;
  434.     $z = cplx($z, 0) unless ref $z;
  435.     return ~i * log(i * $z + sqrt(1 - $z*$z));
  436. }
  437.  
  438. sub atan {
  439.     my ($z) = @_;
  440.     $z = cplx($z, 0) unless ref $z;
  441.     _divbyzero "atan($z)", "i - $z" if ($z == i);
  442.     return i/2*log((i + $z) / (i - $z));
  443. }
  444.  
  445. sub asec {
  446.     my ($z) = @_;
  447.     _divbyzero "asec($z)", $z if ($z == 0);
  448.     return acos(1 / $z);
  449. }
  450.  
  451. sub acsc {
  452.     my ($z) = @_;
  453.     _divbyzero "acsc($z)", $z if ($z == 0);
  454.     return asin(1 / $z);
  455. }
  456.  
  457. sub acosec { Math::Complex::acsc(@_) }
  458.  
  459. sub acot {
  460.     my ($z) = @_;
  461.     $z = cplx($z, 0) unless ref $z;
  462.     _divbyzero "acot($z)", "$z - i" if ($z == i);
  463.     return i/-2 * log((i + $z) / ($z - i));
  464. }
  465.  
  466. sub acotan { Math::Complex::acot(@_) }
  467.  
  468. sub cosh {
  469.     my ($z) = @_;
  470.     my $real;
  471.     unless (ref $z) {
  472.         $z = cplx($z, 0);
  473.         $real = 1;
  474.     }
  475.     my ($x, $y) = @{$z->cartesian};
  476.     my $ex = exp($x);
  477.     my $ex_1 = 1 / $ex;
  478.     return cplx(0.5 * ($ex + $ex_1), 0) if $real;
  479.     return (ref $z)->make(cos($y) * ($ex + $ex_1)/2,
  480.                   sin($y) * ($ex - $ex_1)/2);
  481. }
  482.  
  483. sub sinh {
  484.     my ($z) = @_;
  485.     my $real;
  486.     unless (ref $z) {
  487.         $z = cplx($z, 0);
  488.         $real = 1;
  489.     }
  490.     my ($x, $y) = @{$z->cartesian};
  491.     my $ex = exp($x);
  492.     my $ex_1 = 1 / $ex;
  493.     return cplx(0.5 * ($ex - $ex_1), 0) if $real;
  494.     return (ref $z)->make(cos($y) * ($ex - $ex_1)/2,
  495.                   sin($y) * ($ex + $ex_1)/2);
  496. }
  497.  
  498. sub tanh {
  499.     my ($z) = @_;
  500.     my $cz = cosh($z);
  501.     _divbyzero "tanh($z)", "cosh($z)" if ($cz == 0);
  502.     return sinh($z) / $cz;
  503. }
  504.  
  505. sub sech {
  506.     my ($z) = @_;
  507.     my $cz = cosh($z);
  508.     _divbyzero "sech($z)", "cosh($z)" if ($cz == 0);
  509.     return 1 / $cz;
  510. }
  511.  
  512. sub csch {
  513.     my ($z) = @_;
  514.     my $sz = sinh($z);
  515.     _divbyzero "csch($z)", "sinh($z)" if ($sz == 0);
  516.     return 1 / $sz;
  517. }
  518.  
  519. sub cosech { Math::Complex::csch(@_) }
  520.  
  521. sub coth {
  522.     my ($z) = @_;
  523.     my $sz = sinh($z);
  524.     _divbyzero "coth($z)", "sinh($z)" if ($sz == 0);
  525.     return cosh($z) / $sz;
  526. }
  527.  
  528. sub cotanh { Math::Complex::coth(@_) }
  529.  
  530. sub acosh {
  531.     my ($z) = @_;
  532.     $z = cplx($z, 0) unless ref $z;
  533.     return log($z + sqrt($z*$z - 1));
  534. }
  535.  
  536. sub asinh {
  537.     my ($z) = @_;
  538.     $z = cplx($z, 0) unless ref $z;
  539.     return log($z + sqrt($z*$z + 1));
  540. }
  541.  
  542. sub atanh {
  543.     my ($z) = @_;
  544.     _divbyzero 'atanh(1)', "1 - $z" if ($z == 1);
  545.     $z = cplx($z, 0) unless ref $z;
  546.     my $cz = (1 + $z) / (1 - $z);
  547.     return log($cz) / 2;
  548. }
  549.  
  550. sub asech {
  551.     my ($z) = @_;
  552.     _divbyzero 'asech(0)', $z if ($z == 0);
  553.     return acosh(1 / $z);
  554. }
  555.  
  556. sub acsch {
  557.     my ($z) = @_;
  558.     _divbyzero 'acsch(0)', $z if ($z == 0);
  559.     return asinh(1 / $z);
  560. }
  561.  
  562. sub acosech { Math::Complex::acsch(@_) }
  563.  
  564. sub acoth {
  565.     my ($z) = @_;
  566.     _divbyzero 'acoth(1)', "$z - 1" if ($z == 1);
  567.     $z = cplx($z, 0) unless ref $z;
  568.     my $cz = (1 + $z) / ($z - 1);
  569.     return log($cz) / 2;
  570. }
  571.  
  572. sub acotanh { Math::Complex::acoth(@_) }
  573.  
  574. sub atan2 {
  575.     my ($z1, $z2, $inverted) = @_;
  576.     my ($re1, $im1) = ref $z1 ? @{$z1->cartesian} : ($z1, 0);
  577.     my ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
  578.     my $tan;
  579.     if (defined $inverted && $inverted) {    # atan(z2/z1)
  580.         return pi * ($re2 > 0 ? 1 : -1) if $re1 == 0 && $im1 == 0;
  581.         $tan = $z2 / $z1;
  582.     } else {
  583.         return pi * ($re1 > 0 ? 1 : -1) if $re2 == 0 && $im2 == 0;
  584.         $tan = $z1 / $z2;
  585.     }
  586.     return atan($tan);
  587. }
  588.  
  589. sub display_format {
  590.     my $self = shift;
  591.     my $format = undef;
  592.  
  593.     if (ref $self) {            # Called as a method
  594.         $format = shift;
  595.     } else {                # Regular procedure call
  596.         $format = $self;
  597.         undef $self;
  598.     }
  599.  
  600.     if (defined $self) {
  601.         return defined $self->{display} ? $self->{display} : $display
  602.             unless defined $format;
  603.         return $self->{display} = $format;
  604.     }
  605.  
  606.     return $display unless defined $format;
  607.     return $display = $format;
  608. }
  609.  
  610. sub stringify {
  611.     my ($z) = shift;
  612.     my $format;
  613.  
  614.     $format = $display;
  615.     $format = $z->{display} if defined $z->{display};
  616.  
  617.     return $z->stringify_polar if $format =~ /^p/i;
  618.     return $z->stringify_cartesian;
  619. }
  620.  
  621. sub stringify_cartesian {
  622.     my $z  = shift;
  623.     my ($x, $y) = @{$z->cartesian};
  624.     my ($re, $im);
  625.  
  626.     $x = int($x + ($x < 0 ? -1 : 1) * 1e-14)
  627.         if int(abs($x)) != int(abs($x) + 1e-14);
  628.     $y = int($y + ($y < 0 ? -1 : 1) * 1e-14)
  629.         if int(abs($y)) != int(abs($y) + 1e-14);
  630.  
  631.     $re = "$x" if abs($x) >= 1e-14;
  632.     if ($y == 1)                { $im = 'i' }
  633.     elsif ($y == -1)            { $im = '-i' }
  634.     elsif (abs($y) >= 1e-14)    { $im = $y . "i" }
  635.  
  636.     my $str = '';
  637.     $str = $re if defined $re;
  638.     $str .= "+$im" if defined $im;
  639.     $str =~ s/\+-/-/;
  640.     $str =~ s/^\+//;
  641.     $str = '0' unless $str;
  642.  
  643.     return $str;
  644. }
  645.  
  646. sub stringify_polar {
  647.     my $z  = shift;
  648.     my ($r, $t) = @{$z->polar};
  649.     my $theta;
  650.     my $eps = 1e-14;
  651.  
  652.     return '[0,0]' if $r <= $eps;
  653.  
  654.     my $tpi = 2 * pi;
  655.     my $nt = $t / $tpi;
  656.     $nt = ($nt - int($nt)) * $tpi;
  657.     $nt += $tpi if $nt < 0;            # Range [0, 2pi]
  658.  
  659.     if (abs($nt) <= $eps)        { $theta = 0 }
  660.     elsif (abs(pi-$nt) <= $eps)    { $theta = 'pi' }
  661.  
  662.     if (defined $theta) {
  663.         $r = int($r + ($r < 0 ? -1 : 1) * $eps)
  664.             if int(abs($r)) != int(abs($r) + $eps);
  665.         $theta = int($theta + ($theta < 0 ? -1 : 1) * $eps)
  666.             if ($theta ne 'pi' and
  667.                 int(abs($theta)) != int(abs($theta) + $eps));
  668.         return "\[$r,$theta\]";
  669.     }
  670.  
  671.  
  672.     $nt -= $tpi if $nt > pi;
  673.     my ($n, $k, $kpi);
  674.     
  675.     for ($k = 1, $kpi = pi; $k < 10; $k++, $kpi += pi) {
  676.         $n = int($kpi / $nt + ($nt > 0 ? 1 : -1) * 0.5);
  677.         if (abs($kpi/$n - $nt) <= $eps) {
  678.             $theta = ($nt < 0 ? '-':'').
  679.                  ($k == 1 ? 'pi':"${k}pi").'/'.abs($n);
  680.             last;
  681.         }
  682.     }
  683.  
  684.     $theta = $nt unless defined $theta;
  685.  
  686.     $r = int($r + ($r < 0 ? -1 : 1) * $eps)
  687.         if int(abs($r)) != int(abs($r) + $eps);
  688.     $theta = int($theta + ($theta < 0 ? -1 : 1) * $eps)
  689.         if ($theta !~ m(^-?\d*pi/\d+$) and
  690.             int(abs($theta)) != int(abs($theta) + $eps));
  691.  
  692.     return "\[$r,$theta\]";
  693. }
  694.  
  695. 1;
  696. __END__
  697.  
  698. =head1 NAME
  699.  
  700. Math::Complex - complex numbers and associated mathematical functions
  701.  
  702. =head1 SYNOPSIS
  703.  
  704.     use Math::Complex;
  705.     
  706.     $z = Math::Complex->make(5, 6);
  707.     $t = 4 - 3*i + $z;
  708.     $j = cplxe(1, 2*pi/3);
  709.  
  710. =head1 DESCRIPTION
  711.  
  712. This package lets you create and manipulate complex numbers. By default,
  713. I<Perl> limits itself to real numbers, but an extra C<use> statement brings
  714. full complex support, along with a full set of mathematical functions
  715. typically associated with and/or extended to complex numbers.
  716.  
  717. If you wonder what complex numbers are, they were invented to be able to solve
  718. the following equation:
  719.  
  720.     x*x = -1
  721.  
  722. and by definition, the solution is noted I<i> (engineers use I<j> instead since
  723. I<i> usually denotes an intensity, but the name does not matter). The number
  724. I<i> is a pure I<imaginary> number.
  725.  
  726. The arithmetics with pure imaginary numbers works just like you would expect
  727. it with real numbers... you just have to remember that
  728.  
  729.     i*i = -1
  730.  
  731. so you have:
  732.  
  733.     5i + 7i = i * (5 + 7) = 12i
  734.     4i - 3i = i * (4 - 3) = i
  735.     4i * 2i = -8
  736.     6i / 2i = 3
  737.     1 / i = -i
  738.  
  739. Complex numbers are numbers that have both a real part and an imaginary
  740. part, and are usually noted:
  741.  
  742.     a + bi
  743.  
  744. where C<a> is the I<real> part and C<b> is the I<imaginary> part. The
  745. arithmetic with complex numbers is straightforward. You have to
  746. keep track of the real and the imaginary parts, but otherwise the
  747. rules used for real numbers just apply:
  748.  
  749.     (4 + 3i) + (5 - 2i) = (4 + 5) + i(3 - 2) = 9 + i
  750.     (2 + i) * (4 - i) = 2*4 + 4i -2i -i*i = 8 + 2i + 1 = 9 + 2i
  751.  
  752. A graphical representation of complex numbers is possible in a plane
  753. (also called the I<complex plane>, but it's really a 2D plane).
  754. The number
  755.  
  756.     z = a + bi
  757.  
  758. is the point whose coordinates are (a, b). Actually, it would
  759. be the vector originating from (0, 0) to (a, b). It follows that the addition
  760. of two complex numbers is a vectorial addition.
  761.  
  762. Since there is a bijection between a point in the 2D plane and a complex
  763. number (i.e. the mapping is unique and reciprocal), a complex number
  764. can also be uniquely identified with polar coordinates:
  765.  
  766.     [rho, theta]
  767.  
  768. where C<rho> is the distance to the origin, and C<theta> the angle between
  769. the vector and the I<x> axis. There is a notation for this using the
  770. exponential form, which is:
  771.  
  772.     rho * exp(i * theta)
  773.  
  774. where I<i> is the famous imaginary number introduced above. Conversion
  775. between this form and the cartesian form C<a + bi> is immediate:
  776.  
  777.     a = rho * cos(theta)
  778.     b = rho * sin(theta)
  779.  
  780. which is also expressed by this formula:
  781.  
  782.     z = rho * exp(i * theta) = rho * (cos theta + i * sin theta) 
  783.  
  784. In other words, it's the projection of the vector onto the I<x> and I<y>
  785. axes. Mathematicians call I<rho> the I<norm> or I<modulus> and I<theta>
  786. the I<argument> of the complex number. The I<norm> of C<z> will be
  787. noted C<abs(z)>.
  788.  
  789. The polar notation (also known as the trigonometric
  790. representation) is much more handy for performing multiplications and
  791. divisions of complex numbers, whilst the cartesian notation is better
  792. suited for additions and substractions. Real numbers are on the I<x>
  793. axis, and therefore I<theta> is zero.
  794.  
  795. All the common operations that can be performed on a real number have
  796. been defined to work on complex numbers as well, and are merely
  797. I<extensions> of the operations defined on real numbers. This means
  798. they keep their natural meaning when there is no imaginary part, provided
  799. the number is within their definition set.
  800.  
  801. For instance, the C<sqrt> routine which computes the square root of
  802. its argument is only defined for positive real numbers and yields a
  803. positive real number (it is an application from B<R+> to B<R+>).
  804. If we allow it to return a complex number, then it can be extended to
  805. negative real numbers to become an application from B<R> to B<C> (the
  806. set of complex numbers):
  807.  
  808.     sqrt(x) = x >= 0 ? sqrt(x) : sqrt(-x)*i
  809.  
  810. It can also be extended to be an application from B<C> to B<C>,
  811. whilst its restriction to B<R> behaves as defined above by using
  812. the following definition:
  813.  
  814.     sqrt(z = [r,t]) = sqrt(r) * exp(i * t/2)
  815.  
  816. Indeed, a negative real number can be noted C<[x,pi]>
  817. (the modulus I<x> is always positive, so C<[x,pi]> is really C<-x>, a
  818. negative number)
  819. and the above definition states that
  820.  
  821.     sqrt([x,pi]) = sqrt(x) * exp(i*pi/2) = [sqrt(x),pi/2] = sqrt(x)*i
  822.  
  823. which is exactly what we had defined for negative real numbers above.
  824.  
  825. All the common mathematical functions defined on real numbers that
  826. are extended to complex numbers share that same property of working
  827. I<as usual> when the imaginary part is zero (otherwise, it would not
  828. be called an extension, would it?).
  829.  
  830. A I<new> operation possible on a complex number that is
  831. the identity for real numbers is called the I<conjugate>, and is noted
  832. with an horizontal bar above the number, or C<~z> here.
  833.  
  834.      z = a + bi
  835.     ~z = a - bi
  836.  
  837. Simple... Now look:
  838.  
  839.     z * ~z = (a + bi) * (a - bi) = a*a + b*b
  840.  
  841. We saw that the norm of C<z> was noted C<abs(z)> and was defined as the
  842. distance to the origin, also known as:
  843.  
  844.     rho = abs(z) = sqrt(a*a + b*b)
  845.  
  846. so
  847.  
  848.     z * ~z = abs(z) ** 2
  849.  
  850. If z is a pure real number (i.e. C<b == 0>), then the above yields:
  851.  
  852.     a * a = abs(a) ** 2
  853.  
  854. which is true (C<abs> has the regular meaning for real number, i.e. stands
  855. for the absolute value). This example explains why the norm of C<z> is
  856. noted C<abs(z)>: it extends the C<abs> function to complex numbers, yet
  857. is the regular C<abs> we know when the complex number actually has no
  858. imaginary part... This justifies I<a posteriori> our use of the C<abs>
  859. notation for the norm.
  860.  
  861. =head1 OPERATIONS
  862.  
  863. Given the following notations:
  864.  
  865.     z1 = a + bi = r1 * exp(i * t1)
  866.     z2 = c + di = r2 * exp(i * t2)
  867.     z = <any complex or real number>
  868.  
  869. the following (overloaded) operations are supported on complex numbers:
  870.  
  871.     z1 + z2 = (a + c) + i(b + d)
  872.     z1 - z2 = (a - c) + i(b - d)
  873.     z1 * z2 = (r1 * r2) * exp(i * (t1 + t2))
  874.     z1 / z2 = (r1 / r2) * exp(i * (t1 - t2))
  875.     z1 ** z2 = exp(z2 * log z1)
  876.     ~z1 = a - bi
  877.     abs(z1) = r1 = sqrt(a*a + b*b)
  878.     sqrt(z1) = sqrt(r1) * exp(i * t1/2)
  879.     exp(z1) = exp(a) * exp(i * b)
  880.     log(z1) = log(r1) + i*t1
  881.     sin(z1) = 1/2i (exp(i * z1) - exp(-i * z1))
  882.     cos(z1) = 1/2 (exp(i * z1) + exp(-i * z1))
  883.     abs(z1) = r1
  884.     atan2(z1, z2) = atan(z1/z2)
  885.  
  886. The following extra operations are supported on both real and complex
  887. numbers:
  888.  
  889.     Re(z) = a
  890.     Im(z) = b
  891.     arg(z) = t
  892.  
  893.     cbrt(z) = z ** (1/3)
  894.     log10(z) = log(z) / log(10)
  895.     logn(z, n) = log(z) / log(n)
  896.  
  897.     tan(z) = sin(z) / cos(z)
  898.  
  899.     csc(z) = 1 / sin(z)
  900.     sec(z) = 1 / cos(z)
  901.     cot(z) = 1 / tan(z)
  902.  
  903.     asin(z) = -i * log(i*z + sqrt(1-z*z))
  904.     acos(z) = -i * log(z + sqrt(z*z-1))
  905.     atan(z) = i/2 * log((i+z) / (i-z))
  906.  
  907.     acsc(z) = asin(1 / z)
  908.     asec(z) = acos(1 / z)
  909.     acot(z) = -i/2 * log((i+z) / (z-i))
  910.  
  911.     sinh(z) = 1/2 (exp(z) - exp(-z))
  912.     cosh(z) = 1/2 (exp(z) + exp(-z))
  913.     tanh(z) = sinh(z) / cosh(z) = (exp(z) - exp(-z)) / (exp(z) + exp(-z))
  914.  
  915.     csch(z) = 1 / sinh(z)
  916.     sech(z) = 1 / cosh(z)
  917.     coth(z) = 1 / tanh(z)
  918.     
  919.     asinh(z) = log(z + sqrt(z*z+1))
  920.     acosh(z) = log(z + sqrt(z*z-1))
  921.     atanh(z) = 1/2 * log((1+z) / (1-z))
  922.  
  923.     acsch(z) = asinh(1 / z)
  924.     asech(z) = acosh(1 / z)
  925.     acoth(z) = atanh(1 / z) = 1/2 * log((1+z) / (z-1))
  926.  
  927. I<log>, I<csc>, I<cot>, I<acsc>, I<acot>, I<csch>, I<coth>,
  928. I<acosech>, I<acotanh>, have aliases I<ln>, I<cosec>, I<cotan>,
  929. I<acosec>, I<acotan>, I<cosech>, I<cotanh>, I<acosech>, I<acotanh>,
  930. respectively.
  931.  
  932. The I<root> function is available to compute all the I<n>
  933. roots of some complex, where I<n> is a strictly positive integer.
  934. There are exactly I<n> such roots, returned as a list. Getting the
  935. number mathematicians call C<j> such that:
  936.  
  937.     1 + j + j*j = 0;
  938.  
  939. is a simple matter of writing:
  940.  
  941.     $j = ((root(1, 3))[1];
  942.  
  943. The I<k>th root for C<z = [r,t]> is given by:
  944.  
  945.     (root(z, n))[k] = r**(1/n) * exp(i * (t + 2*k*pi)/n)
  946.  
  947. The I<spaceship> comparison operator, E<lt>=E<gt>, is also defined. In
  948. order to ensure its restriction to real numbers is conform to what you
  949. would expect, the comparison is run on the real part of the complex
  950. number first, and imaginary parts are compared only when the real
  951. parts match.
  952.  
  953. =head1 CREATION
  954.  
  955. To create a complex number, use either:
  956.  
  957.     $z = Math::Complex->make(3, 4);
  958.     $z = cplx(3, 4);
  959.  
  960. if you know the cartesian form of the number, or
  961.  
  962.     $z = 3 + 4*i;
  963.  
  964. if you like. To create a number using the trigonometric form, use either:
  965.  
  966.     $z = Math::Complex->emake(5, pi/3);
  967.     $x = cplxe(5, pi/3);
  968.  
  969. instead. The first argument is the modulus, the second is the angle
  970. (in radians, the full circle is 2*pi).  (Mnmemonic: C<e> is used as a
  971. notation for complex numbers in the trigonometric form).
  972.  
  973. It is possible to write:
  974.  
  975.     $x = cplxe(-3, pi/4);
  976.  
  977. but that will be silently converted into C<[3,-3pi/4]>, since the modulus
  978. must be positive (it represents the distance to the origin in the complex
  979. plane).
  980.  
  981. =head1 STRINGIFICATION
  982.  
  983. When printed, a complex number is usually shown under its cartesian
  984. form I<a+bi>, but there are legitimate cases where the polar format
  985. I<[r,t]> is more appropriate.
  986.  
  987. By calling the routine C<Math::Complex::display_format> and supplying either
  988. C<"polar"> or C<"cartesian">, you override the default display format,
  989. which is C<"cartesian">. Not supplying any argument returns the current
  990. setting.
  991.  
  992. This default can be overridden on a per-number basis by calling the
  993. C<display_format> method instead. As before, not supplying any argument
  994. returns the current display format for this number. Otherwise whatever you
  995. specify will be the new display format for I<this> particular number.
  996.  
  997. For instance:
  998.  
  999.     use Math::Complex;
  1000.  
  1001.     Math::Complex::display_format('polar');
  1002.     $j = ((root(1, 3))[1];
  1003.     print "j = $j\n";        # Prints "j = [1,2pi/3]
  1004.     $j->display_format('cartesian');
  1005.     print "j = $j\n";        # Prints "j = -0.5+0.866025403784439i"
  1006.  
  1007. The polar format attempts to emphasize arguments like I<k*pi/n>
  1008. (where I<n> is a positive integer and I<k> an integer within [-9,+9]).
  1009.  
  1010. =head1 USAGE
  1011.  
  1012. Thanks to overloading, the handling of arithmetics with complex numbers
  1013. is simple and almost transparent.
  1014.  
  1015. Here are some examples:
  1016.  
  1017.     use Math::Complex;
  1018.  
  1019.     $j = cplxe(1, 2*pi/3);    # $j ** 3 == 1
  1020.     print "j = $j, j**3 = ", $j ** 3, "\n";
  1021.     print "1 + j + j**2 = ", 1 + $j + $j**2, "\n";
  1022.  
  1023.     $z = -16 + 0*i;            # Force it to be a complex
  1024.     print "sqrt($z) = ", sqrt($z), "\n";
  1025.  
  1026.     $k = exp(i * 2*pi/3);
  1027.     print "$j - $k = ", $j - $k, "\n";
  1028.  
  1029. =head1 ERRORS DUE TO DIVISION BY ZERO
  1030.  
  1031. The division (/) and the following functions
  1032.  
  1033.     tan
  1034.     sec
  1035.     csc
  1036.     cot
  1037.     asec
  1038.     acsc
  1039.     atan
  1040.     acot
  1041.     tanh
  1042.     sech
  1043.     csch
  1044.     coth
  1045.     atanh
  1046.     asech
  1047.     acsch
  1048.     acoth
  1049.  
  1050. cannot be computed for all arguments because that would mean dividing
  1051. by zero. These situations cause fatal runtime errors looking like this
  1052.  
  1053.     cot(0): Division by zero.
  1054.     (Because in the definition of cot(0), the divisor sin(0) is 0)
  1055.     Died at ...
  1056.  
  1057. For the C<csc>, C<cot>, C<asec>, C<acsc>, C<csch>, C<coth>, C<asech>,
  1058. C<acsch>, the argument cannot be C<0> (zero). For the C<atanh>,
  1059. C<acoth>, the argument cannot be C<1> (one). For the C<atan>, C<acot>,
  1060. the argument cannot be C<i> (the imaginary unit).  For the C<tan>,
  1061. C<sec>, C<tanh>, C<sech>, the argument cannot be I<pi/2 + k * pi>, where
  1062. I<k> is any integer.
  1063.  
  1064. =head1 BUGS
  1065.  
  1066. Saying C<use Math::Complex;> exports many mathematical routines in the
  1067. caller environment and even overrides some (C<sin>, C<cos>, C<sqrt>,
  1068. C<log>, C<exp>).  This is construed as a feature by the Authors,
  1069. actually... ;-)
  1070.  
  1071. The code is not optimized for speed, although we try to use the cartesian
  1072. form for addition-like operators and the trigonometric form for all
  1073. multiplication-like operators.
  1074.  
  1075. The arg() routine does not ensure the angle is within the range [-pi,+pi]
  1076. (a side effect caused by multiplication and division using the trigonometric
  1077. representation).
  1078.  
  1079. All routines expect to be given real or complex numbers. Don't attempt to
  1080. use BigFloat, since Perl has currently no rule to disambiguate a '+'
  1081. operation (for instance) between two overloaded entities.
  1082.  
  1083. =head1 AUTHORS
  1084.  
  1085. Raphael Manfredi <F<Raphael_Manfredi@grenoble.hp.com>> and
  1086. Jarkko Hietaniemi <F<jhi@iki.fi>>.
  1087.  
  1088. =cut
  1089.  
  1090.